package cn.iocoder.yudao.module.product.controller.admin.storespu;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.product.controller.admin.storespu.vo.StoreSpuPageReqVO;
import cn.iocoder.yudao.module.product.controller.admin.storespu.vo.StoreSpuRespVO;
import cn.iocoder.yudao.module.product.controller.admin.storespu.vo.StoreSpuSaveReqVO;
import cn.iocoder.yudao.module.product.controller.admin.storespu.vo.StoreSpuUpdateStatusReqVO;
import cn.iocoder.yudao.module.product.dal.dataobject.spu.ProductSpuDO;
import cn.iocoder.yudao.module.product.dal.dataobject.storespu.StoreSpuDO;
import cn.iocoder.yudao.module.product.service.spu.ProductSpuService;
import cn.iocoder.yudao.module.product.service.storespu.StoreSpuService;
import cn.iocoder.yudao.module.trade.api.store.StoreApi;
import cn.iocoder.yudao.module.trade.api.store.dto.StoreRespDTO;
import com.google.common.collect.Lists;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Tag(name = "管理后台 - 店铺商品SPU")
@RestController
@RequestMapping("/product/store-spu")
@Validated
public class StoreSpuController {

    @Resource
    private StoreSpuService storeSpuService;
    @Resource
    private StoreApi storeApi;
    @Resource
    private ProductSpuService productSpuService;

    @PostMapping("/create")
    @Operation(summary = "创建店铺商品SPU")
//    @PreAuthorize("@ss.hasPermission('product:store-spu:create')")
    public CommonResult<Long> createStoreSpu(@Valid @RequestBody StoreSpuSaveReqVO createReqVO) {
        return success(storeSpuService.createStoreSpu(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新店铺商品SPU")
//    @PreAuthorize("@ss.hasPermission('product:store-spu:update')")
    public CommonResult<Boolean> updateStoreSpu(@Valid @RequestBody StoreSpuSaveReqVO updateReqVO) {
        storeSpuService.updateStoreSpu(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除店铺商品SPU")
    @Parameter(name = "id", description = "编号", required = true)
//    @PreAuthorize("@ss.hasPermission('product:store-spu:delete')")
    public CommonResult<Boolean> deleteStoreSpu(@RequestParam("id") Long id) {
        storeSpuService.deleteStoreSpu(id);
        return success(true);
    }

    @PutMapping("/update-status")
    @Operation(summary = "更新店铺商品 SPU Status")
//    @PreAuthorize("@ss.hasPermission('product:store-spu:update')")
    public CommonResult<Boolean> updateStatus(@Valid @RequestBody StoreSpuUpdateStatusReqVO updateReqVO) {
        storeSpuService.updateSpuStatus(updateReqVO);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得店铺商品SPU")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('product:store-spu:query')")
    public CommonResult<StoreSpuRespVO> getStoreSpu(@RequestParam("id") Long id) {
        StoreSpuDO storeSpu = storeSpuService.getStoreSpu(id);
        StoreSpuRespVO result = BeanUtils.toBean(storeSpu, StoreSpuRespVO.class);
        build(Lists.newArrayList(result));
        return success(result);
    }

    @GetMapping("/page")
    @Operation(summary = "获得店铺商品SPU分页")
//    @PreAuthorize("@ss.hasPermission('product:store-spu:query')")
    public CommonResult<PageResult<StoreSpuRespVO>> getStoreSpuPage(@Valid StoreSpuPageReqVO pageReqVO) {
        PageResult<StoreSpuDO> pageResult = storeSpuService.getStoreSpuPage(pageReqVO);
        PageResult<StoreSpuRespVO> result = BeanUtils.toBean(pageResult, StoreSpuRespVO.class);
        build(result.getList());
        return success(result);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出店铺商品SPU Excel")
//    @PreAuthorize("@ss.hasPermission('product:store-spu:export')")
    @OperateLog(type = EXPORT)
    public void exportStoreSpuExcel(@Valid StoreSpuPageReqVO pageReqVO,
                                    HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<StoreSpuDO> list = storeSpuService.getStoreSpuPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "店铺商品SPU.xls", "数据", StoreSpuRespVO.class,
                BeanUtils.toBean(list, StoreSpuRespVO.class));
    }

    private void build(List<StoreSpuRespVO> list) {
        List<Long> storeIds = CollectionUtils.convertList(list, StoreSpuRespVO::getStoreId);
        List<Long> spuIds = CollectionUtils.convertList(list, StoreSpuRespVO::getProductSpuId);
        List<StoreRespDTO> storeList = storeApi.getStoreList(storeIds);
        List<ProductSpuDO> spuList = productSpuService.getSpuList(spuIds);
        list.forEach(e -> {
            storeList.forEach(x -> {
                if (Objects.equals(x.getId(), e.getStoreId())) {
                    e.setStoreName(x.getName());
                }
            });
            spuList.forEach(x -> {
                if (Objects.equals(x.getId(), e.getProductSpuId())) {
                    e.setProductSpuName(x.getName());
                }
            });
        });
    }

}